package com.smallkingson.ylib.core.utils;

import com.smallkingson.ylib.core.Yr;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


//import javax.servlet.http.HttpServletRequest;

public class YBeanUtils {
    public static Method getSetMethodByFieldName(Class<?> clazz, String fieldName) {
        Method[] methods = clazz.getMethods();
        String methodName = "set" + (fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1));
        for (Method m : methods) {
            if (methodName.equals(m.getName())) {
                return m;
            }
        }
        return null;
    }

    public static boolean isNumType(Class<?> aClass) {

        if (aClass == int.class || aClass == Integer.class
                || aClass == float.class || aClass == Float.class
                || aClass == short.class || aClass == Short.class
                || aClass == long.class || aClass == Long.class
                || aClass == double.class || aClass == Double.class) {
            return true;
        }
        return false;
    }

    public static Method getGetMethodByFieldName(Class<?> clazz, String fieldName) {
        Method[] methods = clazz.getMethods();

        String methodName = "get" + (fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1));

        for (Method m : methods) {
            if (methodName.equals(m.getName())) {
                return m;
            }
        }
        return null;
    }

    /**
     * 通过Method 获取该set 或 get 方法的Method 所对应的字段的名称
     *
     * @param method
     * @return
     */
    public static String getFieldNameFromMethod(Method method) {

        String methodName = method.getName();
        methodName = methodName.substring(3);
        String FieldName = methodName.substring(0, 1).toLowerCase()
                + methodName.substring(1);
        return FieldName;
    }

    /**
     *
     */
    public static boolean isSetMethod(Method method) {

        if (method.getName().startsWith("set")) {
            return true;
        }
        return false;
    }

    /**
     * A.B.Main$User
     *
     * @param clazz User.class
     * @return "User"
     */
    public static String getClassName(Class<?> clazz) {

        String name = clazz.getName();

        name = name.substring(name.lastIndexOf(".") + 1);

        name = name.substring(name.lastIndexOf("$") + 1);

        return name;
    }

    /**
     * 获取所有的get方法
     *
     * @param beanClass
     * @return
     */
    public static List<Method> getGetMethods(Class beanClass) {

        List<Method> methods = new ArrayList<Method>();

        Method[] declaredMethods = beanClass.getDeclaredMethods();
        for (Method method : declaredMethods) {
            String methodName = method.getName();
            if (methodName.startsWith("get") && (!method.equals("getClass"))) {
                methods.add(method);
            }
        }
        return methods;
    }

    /**
     * 获取所有的set方法
     *
     * @param beanClass
     * @return
     */
    public static List<Method> getSetMethods(Class beanClass) {

        List<Method> methods = new ArrayList<Method>();
        for (Method method : beanClass.getMethods()) {
            String methodName = method.getName();
            if (methodName.startsWith("set")) {
                methods.add(method);
            }
        }
        return methods;
    }

    /**
     * @param method
     * @return
     */
    public static boolean isGetMethod(Method method) {

        String methodName = method.getName();
        if (methodName.startsWith("get") && (!methodName.equals("getClass"))) {
            return true;
        }
        return false;
    }


    /**
     * 通过成员变量名获取该成员变量的类型，由于成员变量为私有的，所以需要通过Setter方法获取该方法的参数类型。来获取成员变量名
     *
     * @param javaBeanClass javaBean类型
     * @param fieldName     成员变量名
     * @return 成员变量的名称
     */
    public static Class getPropertyType(Class javaBeanClass, String fieldName) {

        if (fieldName == null || fieldName.trim().length() <= 0) {
            return null;
        }
        String setName = "set" + fieldName.substring(0, 1).toUpperCase()
                + fieldName.substring(1);
        Method[] allMethod = javaBeanClass.getMethods();
        for (Method method : allMethod) {
            if (method.getName().equals(setName)) {
                Class[] paramClass = method.getParameterTypes();
                if (paramClass == null || paramClass.length == 0
                        || paramClass.length > 1) {
                    return null;
                }
                return paramClass[0];
            }
        }
        return null;
    }

    /**
     * 根据给定的 设置bean里对应字段的值
     */

    public static String getFieldNameByMethodName(String getOrSetName) {

        String fieldName = getOrSetName.substring(3);

        fieldName = fieldName.substring(0, 1).toLowerCase()
                + fieldName.substring(1);

        return fieldName;
    }

    /**
     * @param map
     * @param beanClass
     * @return
     * @throws IllegalArgumentException
     * @throws SecurityException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     * @throws UnsupportedEncodingException
     */
    public static Object parseMapToJavaBean(Map<String, ?> map, Class beanClass)
            throws IllegalArgumentException, SecurityException,
            IllegalAccessException, InvocationTargetException,
            NoSuchMethodException, UnsupportedEncodingException {

        Object object = null;
        try {
            object = beanClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        // 获取所有表单名字
        Set<String> parameterNames = map.keySet();
        for (String pname : parameterNames) {

            Field[] fields = beanClass.getDeclaredFields();
            for (Field field : fields) {
                // 找到对应的字段
                if (field.getName().equals(pname)) {
                    // 获得该字段的类型
                    Class fieldType = field.getType();
                    // 找到对应的set方法
                    if (fieldType == String.class) {
                        String value = (String) map.get(pname);
                        beanClass.getMethod(createMethodName(pname),
                                String.class).invoke(object, value);
                    }
                    if (fieldType == Boolean.class) {
                        beanClass.getMethod(createMethodName(pname),
                                Boolean.class).invoke(object,
                                Boolean.parseBoolean((String) map.get(pname)));
                    }
                    if (fieldType == Integer.class) {
                        beanClass.getMethod(createMethodName(pname),
                                Integer.class).invoke(object,
                                Integer.parseInt((String) map.get(pname)));
                    }
                    if (fieldType == Byte.class) {
                        beanClass
                                .getMethod(createMethodName(pname), Byte.class)
                                .invoke(object,
                                        Byte.parseByte((String) map.get(pname)));
                    }
                    if (fieldType == Short.class) {
                        beanClass.getMethod(createMethodName(pname),
                                Short.class).invoke(object,
                                Short.parseShort((String) map.get(pname)));
                    }
                    if (fieldType == Long.class) {
                        beanClass
                                .getMethod(createMethodName(pname), Long.class)
                                .invoke(object,
                                        Long.parseLong((String) map.get(pname)));
                    }
                    if (fieldType == Float.class) {
                        beanClass.getMethod(createMethodName(pname),
                                Float.class).invoke(object,
                                Float.parseFloat((String) map.get(pname)));
                    }
                    if (fieldType == Double.class) {
                        beanClass.getMethod(createMethodName(pname),
                                Double.class).invoke(object,
                                Double.parseDouble((String) map.get(pname)));
                    }
                    if (fieldType == Character.class) {
                        beanClass.getMethod(createMethodName(pname),
                                Character.class).invoke(object,
                                ((String) map.get(pname)).charAt(0));
                    }
                    //
                    if (fieldType == boolean.class) {
                        beanClass.getMethod(createMethodName(pname),
                                boolean.class).invoke(object,
                                Boolean.parseBoolean((String) map.get(pname)));
                    }
                    if (fieldType == int.class) {
                        beanClass.getMethod(createMethodName(pname), int.class)
                                .invoke(object,
                                        Integer.parseInt((String) map
                                                .get(pname)));
                    }
                    if (fieldType == byte.class) {
                        beanClass
                                .getMethod(createMethodName(pname), byte.class)
                                .invoke(object,
                                        Byte.parseByte((String) map.get(pname)));
                    }
                    if (fieldType == short.class) {
                        beanClass.getMethod(createMethodName(pname),
                                short.class).invoke(object,
                                Short.parseShort((String) map.get(pname)));
                    }
                    if (fieldType == long.class) {
                        beanClass
                                .getMethod(createMethodName(pname), long.class)
                                .invoke(object,
                                        Long.parseLong((String) map.get(pname)));
                    }
                    if (fieldType == float.class) {
                        beanClass.getMethod(createMethodName(pname),
                                float.class).invoke(object,
                                Float.parseFloat((String) map.get(pname)));
                    }
                    if (fieldType == double.class) {
                        beanClass.getMethod(createMethodName(pname),
                                double.class).invoke(object,
                                Double.parseDouble((String) map.get(pname)));
                    }
                    if (fieldType == char.class) {
                        beanClass
                                .getMethod(createMethodName(pname), char.class)
                                .invoke(object,
                                        ((String) map.get(pname)).charAt(0));
                    }
                }
            }
        }
        return object;
    }

    public static String createMethodName(String fieldName) {

        return "set" + fieldName.trim().substring(0, 1).toUpperCase()
                + fieldName.trim().substring(1);
    }

    public static <T, V> void setBeanValue(T t, String fieldName, V value)
            throws NoSuchMethodException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {

        String MethodName = YBeanUtils.createMethodName(fieldName);
        Method method = t.getClass().getMethod(MethodName, value.getClass());
        method.invoke(t, value);
    }

    /**
     * 根据request里的请求参数和值 自动给javaBean赋值
     *
     **/
    // public static Object parseRequestToJavaBean(HttpServletRequest
    // request,Class beanClass) throws IllegalArgumentException,
    // SecurityException, IllegalAccessException, InvocationTargetException,
    // NoSuchMethodException, UnsupportedEncodingException{
    // Object object=null;
    // try {
    // object=beanClass.newInstance();
    // } catch (InstantiationException e) {
    // e.printStackTrace();
    // } catch (IllegalAccessException e) {
    // e.printStackTrace();
    // }
    // //获取所有表单名字
    // Enumeration<String> parameterNames=request.getParameterNames();
    // while(parameterNames.hasMoreElements()){
    // String pname=parameterNames.nextElement();
    // Field[] fields=beanClass.getDeclaredFields();
    // for(Field field:fields){
    // //找到对应的字段
    // if(field.getName().equals(pname)){
    // //获得该字段的类型
    // Class fieldType=field.onSetType();
    // //找到对应的set方法
    // if(fieldType==String.class){
    // String value=new
    // String(request.getParameter(pname).getBytes("iso8859-1"),"utf-8");
    // beanClass.getMethod(createMethodName(pname), String.class).invoke(object,
    // value);
    // }
    // if(fieldType==Boolean.class){
    // beanClass.getMethod(createMethodName(pname),Boolean.class).invoke(object,
    // Boolean.parseBoolean(request.getParameter(pname)));
    // }
    // if(fieldType==Integer.class){
    // beanClass.getMethod(createMethodName(pname),Integer.class).invoke(object,
    // Integer.parseInt(request.getParameter(pname)));
    // }
    // if(fieldType==Byte.class){
    // beanClass.getMethod(createMethodName(pname), Byte.class).invoke(object,
    // Byte.parseByte(request.getParameter(pname)));
    // }
    // if(fieldType==Short.class){
    // beanClass.getMethod(createMethodName(pname), Short.class).invoke(object,
    // Short.parseShort(request.getParameter(pname)));
    // }
    // if(fieldType==Long.class){
    // beanClass.getMethod(createMethodName(pname), Long.class).invoke(object,
    // Long.parseLong(request.getParameter(pname)));
    // }
    // if(fieldType==Float.class){
    // beanClass.getMethod(createMethodName(pname), Float.class).invoke(object,
    // Float.parseFloat(request.getParameter(pname)));
    // }
    // if(fieldType==Double.class){
    // beanClass.getMethod(createMethodName(pname), Double.class).invoke(object,
    // Double.parseDouble(request.getParameter(pname)));
    // }
    // if(fieldType==Character.class){
    // beanClass.getMethod(createMethodName(pname),
    // Character.class).invoke(object, request.getParameter(pname).charAt(0));
    // }
    // //
    // if(fieldType==boolean.class){
    // beanClass.getMethod(createMethodName(pname),boolean.class).invoke(object,
    // Boolean.parseBoolean(request.getParameter(pname)));
    // }
    // if(fieldType==int.class){
    // beanClass.getMethod(createMethodName(pname),int.class).invoke(object,
    // Integer.parseInt(request.getParameter(pname)));
    // }
    // if(fieldType==byte.class){
    // beanClass.getMethod(createMethodName(pname), byte.class).invoke(object,
    // Byte.parseByte(request.getParameter(pname)));
    // }
    // if(fieldType==short.class){
    // beanClass.getMethod(createMethodName(pname), short.class).invoke(object,
    // Short.parseShort(request.getParameter(pname)));
    // }
    // if(fieldType==long.class){
    // beanClass.getMethod(createMethodName(pname), long.class).invoke(object,
    // Long.parseLong(request.getParameter(pname)));
    // }
    // if(fieldType==float.class){
    // beanClass.getMethod(createMethodName(pname), float.class).invoke(object,
    // Float.parseFloat(request.getParameter(pname)));
    // }
    // if(fieldType==double.class){
    // beanClass.getMethod(createMethodName(pname), double.class).invoke(object,
    // Double.parseDouble(request.getParameter(pname)));
    // }
    // if(fieldType==char.class){
    // beanClass.getMethod(createMethodName(pname), char.class).invoke(object,
    // request.getParameter(pname).charAt(0));
    // }
    // }
    // }
    // }
    // return object;
    // }

    /**
     * 获取bean的名字 小写的
     *
     * @param beanClass
     * @return
     */
    public static String getBeanName(Class beanClass) {

        String name = beanClass.getName();
        name = name.substring(name.lastIndexOf(".") + 1).toLowerCase();
        return name;
    }

    public static String[] getBeanFieldNames(Class beanClass) {

        Field[] fields = beanClass.getFields();
        String[] names = new String[fields.length];
        for (int i = 0; i < names.length; i++) {
            names[i] = fields[i].getName();
        }
        return names;
    }

    /**
     * class test{ List<Student> stus; }
     *
     * @param field "stus" ---名字为"stus"
     * @return Student.class
     */
    public static Class getListGenericType(Field field) {

        Type mapMainType = field.getGenericType();
        if (mapMainType instanceof ParameterizedType) {
            // 执行强制类型转换
            ParameterizedType parameterizedType = (ParameterizedType) mapMainType;
            // 获取基本类型信息，即Map
            Type basicType = parameterizedType.getRawType();
            System.out.println("基本类型为：" + basicType);
            // 获取泛型类型的泛型参数
            Type[] types = parameterizedType.getActualTypeArguments();
            return (Class) types[0];
        }
        return null;
    }

    public static String getGetMethod(String field) {
        return "get" + field.substring(0, 1).toUpperCase() + field.substring(1);
    }

    public static List<String> getReadableFieldNames(Class<?> clazz) {

        List<String> l = new ArrayList<String>();
        List<Method> getMethods = getGetMethods(clazz);
        for (Method m : getMethods) {
            String name = m.getName().substring(3);
            l.add(name.substring(0, 1).toLowerCase() + name.substring(1));
        }
        return l;
    }

    public static <T> T classNewInstance(Class<T> class1) {

        try {
            Class<?> parentClass = class1.getDeclaringClass();
            if (parentClass == null) {
                Object o = class1.newInstance();
                return class1.newInstance();
            } else {
                Constructor<?>[] c = class1.getDeclaredConstructors();
                T o = (T) c[0].newInstance(classNewInstance(parentClass));
                return o;
            }
        } catch (Exception e) {
            Yr.logError(e);
        }
        return null;
    }

    public static void setOnTypeListener(Object object,
                                         OnTypeListener onTypeListener) {

        if (object.getClass() == int.class || object instanceof Integer) {
            // 整形
            onTypeListener.onInt((Integer) object);
        } else if (object.getClass() == float.class || object instanceof Float) {
            // 浮点型
            onTypeListener.onFloat((Float) object);
        } else if (object instanceof String) {
            // 字符串
            onTypeListener.onString((String) object);

        } else if (object.getClass() == boolean.class
                || object instanceof Boolean) {
            // boolean
            onTypeListener.onBoolean((Boolean) object);
        } else if (object.getClass() == long.class || object instanceof Long) {
            // long
            onTypeListener.onLong((Long) object);
        } else if (object.getClass() == double.class
                || object instanceof Double) {
            // long
            onTypeListener.onDouble((Double) object);
        }

    }

    /**
     * Class User{
     * <p>
     * private int id; }
     *
     * @param t              User
     * @param class_         某个set方法的参数类型
     * @param onTypeListener 根据这个类型做相应的事
     */
    public static <T> void setOnTypeListener(T t, Class class_,
                                             OnTypeListener1<T> onTypeListener) throws Exception {

        if (class_ == int.class || class_ == Integer.class) {
            // 整形
            onTypeListener.onInt(t);
        } else if (class_ == float.class || class_ == Float.class) {
            // 浮点型
            onTypeListener.onFloat(t);
        } else if (class_ == String.class) {
            // 字符串
            onTypeListener.onString(t);

        } else if (class_ == boolean.class || class_ == Boolean.class) {
            // boolean
            onTypeListener.onBoolean(t);

        } else if (class_ == long.class || class_ == Long.class) {
            // long
            onTypeListener.onLong(t);
        } else if (class_ == double.class || class_ == Double.class) {
            onTypeListener.onDouble(t);
        }

    }

    public static void setTypeWatcher(Class<?> beanClass, String fieldName,
                                      TypeWatcher typeWatcher) {
        Field declaredField = null;
        try {
            try {
                declaredField = beanClass.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
                Yr.d(e);
                declaredField = beanClass.getSuperclass().getDeclaredField(fieldName);
            }
            declaredField.setAccessible(true);

            Class<?> type = declaredField.getType();

            if (type == String.class) {

                typeWatcher.onString();
            } else if (type == double.class) {
                typeWatcher.onDouble();
            } else if (type == Double.class) {
                typeWatcher.onDoubleObj();
            } else if (type == int.class) {

                typeWatcher.onInt();
            } else if (type == Integer.class) {

                typeWatcher.onIntObj();
            } else if (type == float.class) {

                typeWatcher.onFloat();
            } else if (type == Float.class) {

                typeWatcher.onFloatObj();
            } else if (type == long.class) {

                typeWatcher.onLong();
            } else if (type == Long.class) {
                typeWatcher.onLongObj();
            } else if (type == boolean.class) {
                typeWatcher.onBoolean();
            } else if (type == Boolean.class) {
                typeWatcher.onBooleanObj();
            }
        } catch (Exception e) {
            Yr.e(fieldName, e);
//			Yr.logError(e);
        }

    }

    public static void setTypeWatcher(Class<?> type, TypeWatcher typeWatcher) {

        try {
            if (type == String.class) {
                typeWatcher.onString();
            } else if (type == double.class) {
                typeWatcher.onDouble();
            } else if (type == Double.class) {
                typeWatcher.onDoubleObj();
            } else if (type == int.class) {

                typeWatcher.onInt();
            } else if (type == Integer.class) {

                typeWatcher.onIntObj();
            } else if (type == float.class) {

                typeWatcher.onFloat();
            } else if (type == Float.class) {

                typeWatcher.onFloatObj();
            } else if (type == long.class) {

                typeWatcher.onLong();
            } else if (type == Long.class) {
                typeWatcher.onLongObj();
            } else if (type == boolean.class) {
                typeWatcher.onBoolean();
            } else if (type == Boolean.class) {
                typeWatcher.onBooleanObj();
            }
        } catch (Exception e) {
            Yr.logError(e);
        }
    }

    public static HashMap toHashMap(Object object, Class clazz) {
        HashMap map = new HashMap();
        try {
            List<Method> getMethods = getGetMethods(clazz);
            for (Method method : getMethods) {
                String fieldName = getFieldNameFromMethod(method);
                map.put(fieldName, method.invoke(object));
            }
        } catch (Exception e) {
            Yr.logError(e);
        }
        return map;
    }

    public static HashMap toHashMap(Object object) {
        return toHashMap(object, object.getClass());
    }

    /**
     * @param obj
     * @param to
     * @param clazz
     * @param <T>
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static <T> void copyFieldsOnClass(T obj, T to, Class clazz) throws InvocationTargetException,
            IllegalAccessException {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Object value = field.get(obj);
            field.set(to, value);
        }
    }

    public static void copyFields(Object obj, Object to, Class clazz) throws InvocationTargetException,
            IllegalAccessException, NoSuchFieldException {
        Field[] fields = clazz.getDeclaredFields();
        Class<?> toClass = to.getClass();
        for (Field field : fields) {
            String name = field.getName();
            Field toField = null;
            try {
                toField = YBeanUtils.getDeclaredFieldFromAll(toClass, name);
            } catch (Exception e) {
                Yr.d(name, e);
                continue;
            }
            if (toField == null) {
                continue;
            }
            toField.setAccessible(true);
            field.setAccessible(true);
            Object value = field.get(obj);
            toField.set(to, value);
        }
    }

    private static Field getDeclaredFieldFromAll(Class<?> toClass, String name) {

        try {
            Field declaredField = toClass.getDeclaredField(name);
            return declaredField;
        } catch (NoSuchFieldException e) {
            Class<?> superclass = toClass.getSuperclass();
            if (superclass == null) {
                return null;
            }
            return getDeclaredFieldFromAll(superclass, name);
        }
    }

    public static interface OnTypeListener {

        void onInt(int value);

        void onFloat(float value);

        void onString(String value);

        void onBoolean(boolean value);

        void onLong(long value);

        void onDouble(double value);

    }

    public static interface TypeWatcher {

        void onString() throws Exception;

        void onDoubleObj() throws Exception;

        void onDouble() throws Exception;

        void onInt() throws Exception;

        void onFloat() throws Exception;

        void onLong() throws Exception;

        void onBoolean() throws Exception;

        void onIntObj() throws Exception;

        void onLongObj() throws Exception;

        void onFloatObj() throws Exception;

        void onBooleanObj() throws Exception;
    }

    public static interface OnTypeListener1<T> {

        void onInt(T t) throws Exception;

        void onFloat(T t) throws Exception;

        void onString(T t) throws Exception;

        void onBoolean(T t) throws Exception;

        void onLong(T t) throws Exception;

        void onDouble(T t) throws Exception;
    }
}